const Service = require("egg").Service;
const crypto = require("crypto");
const { QueryTypes, Op } = require("sequelize");

class UserService extends Service {
  // 搜索用户
  async searchUser() {
    let name = this.ctx.query.name;
    console.log(name);
    try {
      let User = await this.app.model.User.findAll({
        where: { username: { [Op.like]: `%${name}%` } }
      });

      if (!User) return { msg: "查询失败" };

      return User;
    } catch (e) {
      console.log(e);
    }
  }

  // 根据id删除用户
  async deleteUserById() {
    let id = this.ctx.request.body.id;
    let res = await this.app.model.User.destroy({ where: { id } });
    if (!res) return { msg: "删除失败" };
    return {
      msg: "删除成功"
    };
  }
  // 查询所有用户
  async queryUserList() {
    let res = await this.app.model.User.findAll();
    console.log(res);
    return res;
  }

  // 用户注册
  async userRegister() {
    let { ctx, app } = this;
    let { username, password } = this.ctx.request.body;
    console.log(username, password);
    //参数验证
    ctx.validate({
      username: {
        type: "string",
        required: true,
        desc: "用户名",
        range: { min: 5, max: 10 }
      },
      password: {
        type: "string",
        required: true,
        desc: "密码",
        range: { min: 6, max: 16 }
      }
    });

    // 校验失败返回
    if (ctx.paramErrors) {
      return {
        msg: "用户名或密码格式不正确"
      };
    }

    // 用户是否存在
    if (await app.model.User.findOne({ where: { username } })) {
      return {
        msg: "用户已存在"
      };
    }
    // 插入用户数据
    let EncPassword = await this.createPassword(password); //对数据进行加密处理之后存入数据库
    let user = await app.model.User.create({ username, password: EncPassword });

    if (!user) {
      return {
        msg: "用户注册失败"
      };
    }
    return {
      msg: "用户注册成功"
    };
  }

  // 修改用户密码
  async update() {
    let { username, password, id } = this.ctx.request.body;

    console.log(username, password, id);
    let EncPassword = await this.createPassword(password);
    let obj = {
      username,
      password: EncPassword
    };
    let res = await this.app.model.User.update(obj, {
      where: {
        id
      }
    });

    if (!res) return { msg: "修改失败" };

    return {
      msg: "修改成功"
    };
  }

  // 用户登录
  async userSignIn() {
    let { ctx, app } = this;
    let { username, password } = ctx.request.body;
    // 参数验证
    ctx.validate({
      username: {
        type: "string",
        required: true,
        desc: "用户名",
        range: { min: 5, max: 10 }
      },
      password: {
        type: "string",
        required: true,
        desc: "密码",
        range: { min: 6, max: 16 }
      }
    });
    if (ctx.paramErrors) {
      return {
        msg: "用户名或密码格式不正确"
      };
    }
    // 验证用户是否存在
    let userinfo = await app.model.User.findOne({ where: { username } });

    console.log(userinfo);
    if (!userinfo) {
      return {
        msg: "用户不存在"
      };
    }
    // 校验密码是否正确
    if (!(await this.checkPassword(password, userinfo.password))) {
      return {
        msg: "密码不正确"
      };
    }

    let obj = {
      username: userinfo.username,
      password: userinfo.password
    };
    const token = app.jwt.sign(obj, app.config.jwt.secret);

    // 返回用户信息和token
    return {
      userinfo: {
        id: userinfo.id,
        username: userinfo.username
      },
      msg: "登录成功",
      token
    };
  }

  // 加密
  async createPassword(password) {
    const hmac = crypto.createHash("sha256", this.config.crypto.secret);
    hmac.update(password);
    return hmac.digest("hex");
  }
  // 验证密码
  async checkPassword(password, hash_password) {
    // 先对需要验证的密码进行加密
    password = await this.createPassword(password);
    return password === hash_password;
  }
}
module.exports = UserService;
